package com.qingcloud.common.auth.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.qingcloud.base.remote.pojo.CustomerApiFunction;
import com.qingcloud.common.auth.properties.SecurityProperties;
import com.qingcloud.common.auth.util.AuthUtils;
import com.qingcloud.base.constant.SecurityConstants;
import com.qingcloud.base.remote.pojo.MenuDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.util.AntPathMatcher;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 请求权限判断service
 */
@Slf4j
public abstract class DefaultPermissionServiceImpl {

    @Autowired
    private SecurityProperties securityProperties;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    public abstract List<CustomerApiFunction> findFuncByClientId(String clientId);

    public boolean hasPermission(Authentication authentication, String requestMethod, String requestURI) {
        // 前端跨域OPTIONS请求预检放行 也可通过前端配置代理实现

        if (HttpMethod.OPTIONS.name().equalsIgnoreCase(requestMethod)) {
            return true;
        }
        if (!(authentication instanceof AnonymousAuthenticationToken)) {
            //判断是否开启url权限验证
            if (!securityProperties.getAuth().getUrlPermission().getEnable()) {
                return true;
            }
            //超级管理员admin不需认证
            String username = AuthUtils.getUsername(authentication);
            if (SecurityConstants.ADMIN_USER_NAME.equals(username)) {
                return true;
            }

            OAuth2Authentication auth2Authentication = (OAuth2Authentication)authentication;

            String clientId =  auth2Authentication.getOAuth2Request().getClientId();
            //判断应用黑白名单
            if (!isNeedAuth(clientId)) {
                return true;
            }
            log.debug("this clientId {} need auth,auth url [{}],method [{}]", clientId,requestURI,requestMethod);
            //判断不进行url权限认证的api，所有已登录用户都能访问的url
            for (String path : securityProperties.getAuth().getUrlPermission().getIgnoreUrls()) {
                if (antPathMatcher.match(path, requestURI)) {
                    return true;
                }
            }
            log.debug("--------------------->clientID【{}】需要判断权限验证的requestURI:{}",clientId,requestURI);
            List<CustomerApiFunction> apiFunctions = this.findFuncByClientId(clientId);
            if(apiFunctions !=null) {
                for (CustomerApiFunction apiFunction : apiFunctions) {
                    if (StringUtils.isNotEmpty(apiFunction.getUrl()) && antPathMatcher.match(apiFunction.getUrl(), requestURI)) {
                        String dataString = apiFunction.getAuthExpired();
                        int dateCompare = DateUtil.compare(DateUtil.parseDate(dataString), new Date());
                        if (dateCompare > 0) {
                            log.error("---------------->API 授权访问时间已经到期，请联系管理员续期！");
                            return false;
                        }
                        return true;
                    }
                }
            }
            return true;
        }
        return false;
    }

    /**
     * 判断应用是否满足白名单和黑名单的过滤逻辑
     * @param clientId 应用id
     * @return true(需要认证)，false(不需要认证)
     */
    private boolean isNeedAuth(String clientId) {
        boolean result = true;
        //白名单
        List<String> includeClientIds = securityProperties.getAuth().getUrlPermission().getIncludeClientIds();
        //黑名单
        List<String> exclusiveClientIds = securityProperties.getAuth().getUrlPermission().getExclusiveClientIds();
        if (includeClientIds.size() > 0) {
            result = includeClientIds.contains(clientId);
        } else if(exclusiveClientIds.size() > 0) {
            result = !exclusiveClientIds.contains(clientId);
        }
        return result;
    }
}
